"""
用户管理相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user

# 创建蓝图
user_bp = Blueprint('user', __name__, url_prefix='/user')

@user_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create_user():
    """创建用户"""
    # 临时实现，返回一个简单的页面
    form_errors = {}  # 初始化表单错误字典
    if request.method == 'POST':
        flash('用户创建成功')
        return redirect(url_for('user.user_list'))
    return render_template('user_form.html', is_edit=False, form_errors=form_errors)

@user_bp.route('/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def edit_user(user_id):
    """编辑用户"""
    # 临时实现，返回一个简单的页面
    form_errors = {}  # 初始化表单错误字典
    
    # 获取用户信息
    from app.models import User
    user = User.query.get_or_404(user_id)
    
    if request.method == 'POST':
        flash('用户信息更新成功')
        return redirect(url_for('user.user_list'))
    return render_template('user_form.html', is_edit=True, user=user, form_errors=form_errors)

@user_bp.route('/list')
@login_required
def user_list():
    """用户列表"""
    # 检查权限，只有管理员可以查看用户列表
    if current_user.role != 'admin':
        flash('您没有权限访问此页面')
        return redirect(url_for('main.home'))
    
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 10
    
    # 获取筛选参数
    search = request.args.get('search', '')
    department_filter = request.args.get('department_filter', '')
    position_filter = request.args.get('position_filter', '')
    status_filter = request.args.get('status_filter', '')
    role_filter = request.args.get('role_filter', '')
    
    # 获取用户列表
    from app.models import User
    from app import db
    
    # 构建查询
    query = User.query
    
    # 应用搜索条件
    if search:
        query = query.filter(
            db.or_(
                User.name.like(f'%{search}%'),
                User.username.like(f'%{search}%'),
                User.email.like(f'%{search}%')
            )
        )
    
    # 应用筛选条件
    if department_filter:
        query = query.filter(User.department == department_filter)
    
    if position_filter:
        query = query.filter(User.position == position_filter)
    
    if status_filter:
        query = query.filter(User.status == status_filter)
    
    if role_filter:
        query = query.filter(User.role == role_filter)
    
    # 分页查询
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    
    # 获取用户统计数据
    from app.services import UserService
    stats = UserService.get_user_stats()
    
    # 获取所有部门和职位列表，用于筛选
    departments = db.session.query(User.department).distinct().filter(User.department.isnot(None)).all()
    departments = [dept[0] for dept in departments if dept[0] is not None]
    
    positions = db.session.query(User.position).distinct().filter(User.position.isnot(None)).all()
    positions = [pos[0] for pos in positions if pos[0] is not None]
    
    return render_template('user_list.html', 
                          users=pagination.items,
                          pagination=pagination,
                          stats=stats,
                          departments=departments,
                          positions=positions,
                          search=search,
                          department_filter=department_filter,
                          position_filter=position_filter,
                          status_filter=status_filter,
                          role_filter=role_filter,
                          page=page,
                          per_page=per_page,
                          total=pagination.total,
                          total_pages=pagination.pages)

@user_bp.route('/<int:user_id>')
@login_required
def view_user(user_id):
    """查看用户详情"""
    from app.models import User
    
    # 获取用户信息
    user = User.query.get_or_404(user_id)
    
    # 获取用户权限
    system_permissions = ['dashboard', 'project', 'customer', 'system', 'report', 'setting']
    user_permissions = []  # 这里应该从数据库获取用户的实际权限
    
    # 获取用户数据权限
    user_data_permission = 'self'  # 这里应该从数据库获取用户的实际数据权限
    
    return render_template('user_detail.html', 
                          user=user,
                          system_permissions=system_permissions,
                          user_permissions=user_permissions,
                          user_data_permission=user_data_permission)